import { dingTalkApi, dTalkApiUtil } from 'dingtalk-app';
import dTalkApiUtils from './../core/lib/util/dTalkApiUtils';
import * as rq from 'request-promise'
import env from './../config/env';
import * as moment from 'moment';
import { cooperateModel } from "./../model/CooperateModel";
import { instrumentModel } from "./../model/InstrumentModel";
import { sysLogModel } from "./../model/SysLogModel";
import { monthRoleModel } from "./../model/MonthRoleModel";

export class MonthService {

    /**
     * @description 报表导入
     * @author 阳朔
     * @param {*} data 
     */
    async importExcel (data :any ,authorization :string ,date :string) {

        let user:any = dingTalkApi.decode(authorization);
        let excelList :any[] = data.data ;//获取到得数据
        // let date = moment().subtract(1, "M").toDate() ;//更新频率 1个月
        // let findCooperate :any = await cooperateModel.find({createDate : { $gte: date }}) ;
        // let findInstrument :any = await instrumentModel.find({createDate : { $gte: date }}) ;
        let findCooperate :any = await cooperateModel.find({yearMonth : date }) ;
        let findInstrument :any = await instrumentModel.find({yearMonth : date }) ;
        if(findCooperate.length > 0){
            for (let k = 0; k < findCooperate.length; k++) {
                let coo :any = findCooperate[k];
                await cooperateModel.remove({ _id : coo._id});
            }
            this.setLog(user,'修改当月的报表','修改') ;
        }else{
            this.setLog(user,'创建了新报表','添加') ;
        }
        if(findInstrument.length > 0){
            for (let j = 0; j < findInstrument.length; j++) {
                let ins :any = findInstrument[j];
                await instrumentModel.remove({ _id : ins._id});
            }
        }
        for (let i = 1; i < excelList.length; i++) {
            let dataList :any[] = excelList[i];

            if(dataList.length == 0){
                await this.pushInstrumentList(excelList , i ,date) ;
                break ;
            }
            await cooperateModel.create({      //按合作模式投放报表
                typeName : dataList[0] ,       //合作类型
                num : dataList[1] ,            //台数
                monthTask : dataList[2] ,      //本月任务
                monthDone : dataList[3] ,      //本月完成
                doneRate : dataList[4] ,       //完成率
                momDone : dataList[5] ,        //环比完成     
                momRate : dataList[6] ,        //环比率
                samePeriodTask : dataList[7] , //同期任务
                samePeriodDone : dataList[8] , //同期完成
                samePeriodRate : dataList[9] , //同期完成率
                cumulativeTask : dataList[10] , //累计任务
                cumulativeDone : dataList[11] , //累计完成
                cumulativeRate : dataList[12] , //累计完成率
                yearMonth : date
            }) ;
        }

        return { code : 100 } ;

    }

    /**
     * @description 遍历 按仪器类型投放报表
     * @author 阳朔
     * @param {any[]} dataList 
     * @param {number} index 
     * @returns 
     */
    async pushInstrumentList (dataList :any[] , index :number ,date :string){

        let instrumentList :any[] = [] ;  //按仪器类型投放报表
        for (let i = index + 2 ; i < dataList.length; i++) {
            let instrument :any[] = dataList[i];
            await instrumentModel.create({      //按仪器类型投放报表
                typeName : instrument[0] ,       //仪器类型
                num : instrument[1] ,            //台数
                monthTask : instrument[2] ,      //本月任务
                monthDone : instrument[3] ,      //本月完成
                doneRate : instrument[4] ,       //完成率
                momDone : instrument[5] ,        //环比完成     
                momRate : instrument[6] ,        //环比率
                samePeriodTask : instrument[7] , //同期任务
                samePeriodDone : instrument[8] , //同期完成
                samePeriodRate : instrument[9] , //同期完成率
                cumulativeTask : instrument[10] , //累计任务
                cumulativeDone : instrument[11] , //累计完成
                cumulativeRate : instrument[12] , //累计完成率
                yearMonth : date
            })
        }
    }

    //创建日志
    async setLog (user :any , detail :string , action :string ) {
        await sysLogModel.create({
            userName : user.name ,
            detail : detail ,
            action : action 
        }) ;
    }

    /**
     * @description 获取log日志
     * @author 阳朔
     */
    async getLogList (res :any) {
        let skip: number = res.skip - 0;
        let limit: number = res.limit - 0;
        let result = await sysLogModel.find().sort({createDate : -1}).skip(skip).limit(limit); ;
        let count :number = await sysLogModel.count({});
        return { code : 100 , data : result , count : count } ;
    }

    /**
     * @description 
     * @author 阳朔
     */
    async queryIns (res :any) {

        let findDate :string = res.date ;
        let date : any = '' ;
        if(findDate)
            date = findDate ;
        else
            date = moment().subtract(1, "M").format('YYYY-MM');
            // date = moment().subtract(1, "M").toDate() ;//更新频率 1个月
        let result :any = await instrumentModel.find({ yearMonth : date }) ;
        if(result.length == 0 )
            return { code : 101 };
        return { code : 100 , data : result } ;
    }

    /**
     * @description 
     * @author 阳朔
     */
    async queryCoo (res :any) {
        let findDate :string = res.date ;
        let date : any = '' ;
        if(findDate)
            date = findDate ;
        else
            date = moment().subtract(1, "M").format('YYYY-MM');
            // date = moment().subtract(1, "M").toDate() ;//更新频率 1个月
        let result :any = await cooperateModel.find({ yearMonth : date }) ;
        if(result.length == 0 )
            return { code : 101 };
        return { code : 100 , data : result } ;
    }

    /**
     * @description 获取权限列表
     * @author 阳朔
     * @returns 
     */
    async queryRoleList () {

        let result :any = await monthRoleModel.find().sort({createDate : -1 }) ;
        return { code : 100 , data : result } ;
    }

    /**
     * @description 添加权限
     * @author 阳朔
     * @param {*} res 
     * @returns 
     */
    async createRole ( res :any ){
        let userList :any = res.userInfo ;

        for (let i = 0; i < userList.length; i++) {
            let element = userList[i];
            let findUser :any = await monthRoleModel.findOne({userId : element.emplId });
            if(findUser){
                return { code : 101 } ;
            }
        }

        for (let j = 0; j < userList.length; j++) {
            let element = userList[j];
            await monthRoleModel.create({userId : element.emplId , userName : element.name , avatar : element.avatar , isEnable : 0 }) ;
        }
        return { code : 100 } ;
    }

    /**
     * @description 根据userId 删除 role
     * @author 阳朔
     * @param {*} res 
     * @returns 
     */
    async deleteRoleByUserId ( res :any ){

        let userId :string = res.userId ;
        await monthRoleModel.remove({userId : userId });
        return { code : 100 };
    }

    async editIsEnable ( res :any ) {
        let isEnable :number = res.isEnable ;
        let _id :string = res._id ;
        let result :any = await monthRoleModel.update({_id : _id},{isEnable : isEnable },{upsert : false }) ;
        return { code : 100 };
    }

    async getRole ( authorization :string ) {

        let user:any = dingTalkApi.decode(authorization);
        let findOne :any = await monthRoleModel.findOne({userId : user.userId });
        if(!findOne || findOne.isEnable == 1){
            return { code : 101 } ;
        }
        return {code : 100 };
    }
}

let monthService = new MonthService();
export default monthService;
